﻿#include "Cpu.h"
#include <string>
#include <format>

#pragma comment(lib, "Pdh.lib")
Cpu::Cpu()
{
    this->_cpu = new char[20];
    this->_memory = new char[20];
    this->_pMemoryStatus = new MEMORYSTATUSEX;
    this->_pMemoryStatus->dwLength = sizeof(MEMORYSTATUSEX);
    this->_pLastIdleTime = new FILETIME;
    this->_pLastKernelTime = new FILETIME;
    this->_pLastUserTime = new FILETIME;
    GetSystemTimes(this->_pLastIdleTime, this->_pLastKernelTime, this->_pLastUserTime);
}

void Cpu::setInvokeFrame(USHORT frame)
{
    this->_invokeFrame = frame;
}

char* Cpu::getCpuRate() const
{
    return this->_cpu;
}

char* Cpu::getMemory() const
{
    return this->_memory;
}

long long Cpu::compareTime(const FILETIME* lastTime, const FILETIME* nowTime) const
{
    return this->timeToInt(nowTime) - this->timeToInt(lastTime);
}

void Cpu::dealCpu(int idel, int kernel, int user) const
{
    if(kernel + user == 0)
    {
        return;
    }
    // (总时间-空闲时间)/总时间 好像只能求当前程序所在核心的利用率
    float rate = 100.0*(kernel + user - idel)/(kernel + user);
    // float rate = 100.0*(kernel + user)/(kernel + user + idel);
    std::string s = "cpu: ";
    s += std::format("{:.2f}", 100.0*(kernel + user - idel)/(kernel + user));
    s += "%";
    _memccpy(this->_cpu, s.c_str(), '\0', s.size() + 1);
}

void Cpu::dealMemory() const
{
    const float Byte2MB = 1024 * 1024 * 1024.0;
    // this->_pMemoryStatus->ullAvailPhys 当前可用
    // this->_pMemoryStatus->ullTotalPhys 总大小
    std::string s = "内存: ";
    s += std::format("{:.1f}", (this->_pMemoryStatus->ullTotalPhys - this->_pMemoryStatus->ullAvailPhys) / Byte2MB);
    s += "/";
    s += std::format("{:.1f}", this->_pMemoryStatus->ullTotalPhys / Byte2MB);
    _memccpy(this->_memory, s.c_str(), '\0', s.size() + 1);
}

long long Cpu::timeToInt(const FILETIME* fTime) const
{
    LARGE_INTEGER li;
    li.LowPart = fTime->dwLowDateTime;
    li.HighPart = fTime->dwHighDateTime;
    return li.QuadPart;
}
